// api.js
const baseUrl = "http://www.itoloan.com"; //服务器地址
var loc = window.location.href;
var index = loc.lastIndexOf("\/");
str = loc.substring(index + 1, loc.length);
console.log('参数为' + str);
console.log(window.location);
function locationPage() {
    location.href = "transaction/";
}
//如果当前页面是行情页
//url存在传token，将token保存

//不存在，直接显示登录，不进行一下操作
//如果不是行情页
//如果有token，进行下一步操作
//没有，返回登录

if(window.location.search != '' && loc.indexOf('quotation') != -1) {
    $('.back-button').click(function () {

        if(phoneType.indexOf("iOS") != -1){
            window.webkit.messageHandlers.iosLocation.postMessage();
        }
        else{
            location.href = "back";
        }
    });

    // $('.back-button').click(function() {
    //     history.go(-1);
    // });
    // $('.back-title').click(function() {
    //     history.go(-1);
    // });
	console.log('有参');
	// var tokenArr = location.search.substring(1).split('=');
    var tokenArr = location.search.substring(1);
    var accessToken="",phoneType = "";
    if(tokenArr.indexOf("&") != -1){
        var testArr = tokenArr.split("&");//a=1,b=1

        //用于拿到token以及手机设备类型
        accessToken = testArr[0].split("=")[1];
        phoneType = testArr[1].split("=")[1];
    }
	// if(tokenArr[0] == 'token') {
	// 	var tokenStr = tokenArr[1];
	// }
    console.log(accessToken,phoneType);
	sessionStorage.setItem('accessToken', accessToken);
    sessionStorage.setItem("phoneType",phoneType);
    // $('.back-button').click(function () {
    //     //     // location.href = "back";
    //     //
    //     //         window.webkit.messageHandlers.iosLocation.postMessage();
    //     //
    //     // });
	//var token = sessionStorage.getItem("user"); //获取token

	$(function() {
        var myChart = echarts.init(document.getElementById("chart-list01"));
		//var user = sessionStorage.getItem('user');
		// 点击更多跳转至买卖列表
		$('.quo-more-span').click(function() {
			window.location = 'buyandsellList/';
		});
		// 我要卖出
		$('.quo-need-sell').click(function() {
			window.location = 'sell/'
		});
		// 跳转至交易记录
		$('.transaction-record').click(function() {
			console.log('交易记录');
			window.location = 'transaction/';
		});
		//获取图表数据
		$.ajax({
			headers: {
                accessToken: accessToken
			},
			type: "post",
			url: baseUrl + "/api/trade/dealLine",//更改------
			async: false,
			success: function(res) {
				var list, xData, yData, code;
				xData = [];
				yData = [];
				list = res.data.deal_line;
				code = res.data.had_cre;
				for(var i = 0; i < list.length; i++) {
					xData.push(list[i].date);
					yData.push(list[i].price);
				}

				var option = {
					//X轴
					xAxis: {
						type: 'category',
						//						boundaryGap: false,
						data: xData,
						//坐标轴颜色
						axisLine: {
							lineStyle: {
								color: '#eaeaea',
								borderWidth: 1
							},
							// show : false
						},
						//x轴文字旋转
						axisLabel: {
							show: true,
							rotate: 0,
							interval: 0
						},
						splitLine: {
							show: false //去掉网格线
						}
					},

					yAxis: {
						type: "value",
						axisLine: {
							lineStyle: {
								color: '#eaeaea',
								borderWidth: 1
							}
						},
						splitLine: {
							show: false
						},
						borderWidth: 0,
						data: yData,
					},
					series: [{
						type: "line",
						data: yData,
						itemStyle: {
							normal: {
								label: {
									show: true
								}
							}
						}
					}],
					grid: { //图表距离边框的距离					
						borderWidth: 0, //去掉右上边框	
						x: 30,
						y: 20,
						x2: 20,
						y2: 20,

					},

				};

				if(option && typeof option === "object") {
					myChart.setOption(option, true);
				}
				$('.quo-chart-code').html(code)

			}
		});

		//获取列表数据
		$.ajax({
			headers: {
                accessToken: accessToken //此处放置请求到的用户token
			},
			type: "post",
			url: baseUrl + "/api/trade/dealList",
			data: {
				'page': 1,
			},
			async: false,
			success: function(res) {
                console.log(res);
				var list = res.data.deal_list;
				if(list.length > 0) {
					for(var i = 0; i < list.length; i++) {
					    if(list[i].rest_amount != 0){
                            var imgStr = "<img src=\"" + list[i].avatar + "\" />";
                            str =
                                "<li>\n" +
                                "<div class=\"quo-user-con-img\">\n" +
                                imgStr +
                                "</div>\n" +
                                "<div class=\"quo-user-con-price\">\n" +
                                "<span>￥</span>\n" +
                                "<span>" + list[i].unit_price + "</span>\n" +
                                "</div>\n" +
                                "<div class=\"quo-user-con-shengYu\">\n" +
                                " <span class=\"quo-shengYu\">" + list[i].rest_amount + "</span>\n" +
                                "<span>/</span>\n" +
                                "<span class=\"quo-sell\">" + list[i].total_amount + "</span>\n" +
                                "</div>\n" +
                                "</li>"

                            $(".quo-user-con ul").append(str);
                        }


					}
					//页面跳转
					$('.quo-user-con ul li').each(function(index) {

						$(this).click(function() {

							// window.location = 'buy.html?id=' + list[index].deal_id;
							// window.location = 'buy/' + list[index].deal_id;
                            sessionStorage.setItem("id", list[index].deal_id);
                            window.location = 'buy/';

						})

					})
				} else {
					$('.quo-user-con ul').html('暂无数据');

				}

			}

		})
	});

} else {
	//var tokenStr = '1.gjvg03loo10qqatoplwdwh6zcln1dfdenawk05ljwtsz2z3oeafld4urf7qmsvoa';
	var accessToken = sessionStorage.getItem("accessToken"); //获取token
	if(accessToken) {
	    //价格数量时间排序的页面
		if(loc.indexOf('buyandsellList') != -1) {

			//buyandselllist.js
			$(function() {
				$('.back-button').click(function() {
					history.go(-1);
				});
                $('.back-title').click(function() {
                    history.go(-1);
                });
                var newData;
				//排序方式1价格2数量3时间
				var defaultIndex = 0; //默认是价格排序，下标为0，切换进行下标改变
				$.ajax({
					type: "post",
					headers: {
                        accessToken: accessToken
					},
					url: "http://www.itoloan.com/api/trade/dealList",
					data: {
						"order_by": "1"
					},
					async: false,
					success: function(backData) {
						console.log(backData.data.deal_list);
						newData = backData.data.deal_list;

						for(var g = 0; g < newData.length; g++) {
							str = "<li>\n" +
								"                        <div class=\"bas-head-img\">\n" +
								"                            <img src=\"" + newData[g].avatar + "\" alt=\"\">\n" +
								"                        </div>\n" +
								"                        <div class=\"bas-buy-price\">\n" +
								"                            <span>￥</span>\n" +
								"                            <span>" + newData[g].unit_price + "</span>\n" +
								"                        </div>\n" +
								"                        <div class=\"bas-shengyu-sell\">\n" +
								"                            <span class=\"bas-shengyu-span\">" + newData[g].rest_amount + "</span>\n" +
								"                            <span>/</span>\n" +
								"                            <span>" + newData[g].total_amount + "</span>\n" +
								"                        </div>\n" +
								"                    </li>";
							$(".bas-list-content ul").append(str);
							//页面跳转

						}



					},
					complete: function(data) {
						//console.log(data)
					},
					dataType: "json"
				});
                //点击价格，数量，时间进行切换排序
                $(".bas-list-classification span").click(function() {
                    $(".bas-list-content ul").find("li").remove();
                    $(".bas-list-classification span").css({
                        color: "#666",
                        "font-size": ".13rem"
                    });
                    $(this).css({
                        color: "#000",
                        "font-size": ".16rem"
                    });
                    defaultIndex = $(this).index(); //拿到下标进行排序
                    //按价格排序
                    if(Number(defaultIndex) === 0) {
                        $.ajax({
                            type: "post",
                            headers: {
                                accessToken: accessToken
                            },
                            url: "http://www.itoloan.com/api/trade/dealList",
                            data: {
                                "order_by": "1"
                            },
                            async: false,
                            success: function(backData) {
                                console.log(backData.data.deal_list);
                                newData = backData.data.deal_list;

                                for(var g = 0; g < newData.length; g++) {
                                    str = "<li>\n" +
                                        "                        <div class=\"bas-head-img\">\n" +
                                        "                            <img src=\"" + newData[g].avatar + "\" alt=\"\">\n" +
                                        "                        </div>\n" +
                                        "                        <div class=\"bas-buy-price\">\n" +
                                        "                            <span>￥</span>\n" +
                                        "                            <span>" + newData[g].unit_price + "</span>\n" +
                                        "                        </div>\n" +
                                        "                        <div class=\"bas-shengyu-sell\">\n" +
                                        "                            <span class=\"bas-shengyu-span\">" + newData[g].rest_amount + "</span>\n" +
                                        "                            <span>/</span>\n" +
                                        "                            <span>" + newData[g].total_amount + "</span>\n" +
                                        "                        </div>\n" +
                                        "                    </li>";
                                    $(".bas-list-content ul").append(str);
                                }
                                // $(".bas-list-content ul li").click(function() {
                                //
                                //         var index = $(this).index();
                                //         var id = newData[index].deal_id;
                                //
                                //         // window.location = 'buy.html/' + id;
                                //         sessionStorage.setItem("id",id);//传参deal_id
                                //         window.location.href = 'buy/';
                                //
                                //
                                // })
                            },
                            dataType: "json"
                        })
                    }
                    //按售出量排序
                    else if(Number(defaultIndex) === 1) {
                        $.ajax({
                            type: "post",
                            headers: {
                                accessToken: accessToken
                            },
                            url: "http://www.itoloan.com/api/trade/dealList",
                            data: {
                                "order_by": "2"
                            },
                            async: true,
                            success: function(backData) {
                                console.log(backData.data.deal_list);
                                newData = backData.data.deal_list;

                                for(var g = 0; g < newData.length; g++) {
                                    str = "<li>\n" +
                                        "    <div class=\"bas-head-img\">\n" +
                                        "                            <img src=\"" + newData[g].avatar + "\" alt=\"\">\n" +
                                        "                        </div>\n" +
                                        "                        <div class=\"bas-buy-price\">\n" +
                                        "                            <span>￥</span>\n" +
                                        "                            <span>" + newData[g].unit_price + "</span>\n" +
                                        "                        </div>\n" +
                                        "                        <div class=\"bas-shengyu-sell\">\n" +
                                        "                            <span class=\"bas-shengyu-span\">" + newData[g].rest_amount + "</span>\n" +
                                        "                            <span>/</span>\n" +
                                        "                            <span>" + newData[g].total_amount + "</span>\n" +
                                        "                        </div>\n" +
                                        "                    </li>";
                                    $(".bas-list-content ul").append(str);
                                }
                                // $(".bas-list-content ul li").each(function(index) {
                                //     $(this).click(function() {
                                //
                                //         var id = newData[index].deal_id;
                                //
                                //         // window.location = 'buy.html/' + id;
                                //         sessionStorage.setItem("id",id);//传参deal_id
                                //         window.location.href = 'buy/';
                                //
                                //     })
                                // })
                            },
                            dataType: "json"
                        })
                    }
                    //按时间排序
                    else {
                        $.ajax({
                            type: "post",
                            headers: {
                                accessToken: accessToken
                            },
                            url: "http://www.itoloan.com/api/trade/dealList",
                            data: {
                                "order_by": "3"
                            },
                            async: true,
                            success: function(backData) {
                                console.log(backData.data.deal_list);
                                newData = backData.data.deal_list;
                                //ajax成功拿到数据，1为价格，进行按价格重新排序
                                //for循环排序，页面打开之后默认排序为价格，此处进行处理

                                for(var g = 0; g < newData.length; g++) {
                                    str = "<li>\n" +
                                        "                        <div class=\"bas-head-img\">\n" +
                                        "                            <img src=\"" + newData[g].avatar + "\" alt=\"\">\n" +
                                        "                        </div>\n" +
                                        "                        <div class=\"bas-buy-price\">\n" +
                                        "                            <span>￥</span>\n" +
                                        "                            <span>" + newData[g].unit_price + "</span>\n" +
                                        "                        </div>\n" +
                                        "                        <div class=\"bas-shengyu-sell\">\n" +
                                        "                            <span class=\"bas-shengyu-span\">" + newData[g].rest_amount + "</span>\n" +
                                        "                            <span>/</span>\n" +
                                        "                            <span>" + newData[g].total_amount + "</span>\n" +
                                        "                        </div>\n" +
                                        "                    </li>";
                                    $(".bas-list-content ul").append(str);
                                    // $(".bas-list-content ul li").each(function(index) {
                                    //     $(this).click(function() {
                                    //
                                    //         var id = newData[index].deal_id;
                                    //
                                    //         // window.location = 'buy/' + id;
                                    //         sessionStorage.setItem("id",id);//传参deal_id
                                    //         window.location.href = 'buy/';
                                    //
                                    //     })
                                    // })
                                }
                            },
                            dataType: "json"
                        })
                    }
                });
                $(".bas-list-content ul").on("click","li",function() {
                    console.log(1)
                    var index = $(this).index();

                    //
                    //
                    var id = newData[index].deal_id;
                    console.log(index,id);
                    //
                    // // window.location = 'buy/' + id;
                    //<link rel="stylesheet" href="{{ config('app.url') }}/sale/css/pageAll.css">
                    console.log("{{ config('app.url') }}/buy/");

                    sessionStorage.setItem("id",id);//传参deal_id
                    window.location = "../buy";
                    //window.location = "{{ config('app.url') }}/buy";
                    // var s = "{{ config('app.url') }}/buy";
                    // console.log(s);


                });
			});

		} else if(loc.indexOf('sell') != -1 && loc.indexOf("buyandsellList") == -1) {
		    var accessToken = sessionStorage.getItem("accessToken");
			//sell.js
			$(function() {
				$('.back-button').click(function() {
					history.go(-1);
				});
				//有蒙版，点击蒙版让选择支付方式隐藏掉
				// $(".posi-block").click(function () {
				//     $(this).css({display:"none"});
				//     $(".change-pay").css({display:"none"})
				// });
				var payPass = "";
				var pw = '';

				var price, num, total_price;
				//输入支付密码
				$(".input-pass input").on("input", function() {
					var maxLength = 6; //定义最大输入长度

					//每输入一个字符
					var passLen = $(this).val().length;
					if(passLen <= maxLength) {
						$(".input-pass").find("li").each(function() {
							$(this).find("img").css({
								display: "none"
							})
						});
						pw = $(this).val();
						console.log(pw);
						for(var h = 0; h < passLen; h++) {
							$(".input-pass").find("li").eq(h).find("img").css({
								display: "block"
							});

						}
						console.log(passLen)

					} else {
						return;

					}
					// else{
					//     return;
					// }
					payPass = pw;
				});
				$.ajax({
					headers: {
						'accessToken': accessToken,
						contentType: "application/x-www-form-urlencoded"
					},
					type: "post",
					url: "http://www.itoloan.com/api/trade/sellPage",
					data: {},
					async: true,
					success: function(backData) {

						var data = backData.data;
						console.log(data);
						var dataNum = Number(data.amount).toFixed(0);
						console.log(dataNum);
						$(".user-data-sell").html(data.nickname);
						$(".shengyu-data-sell").html(dataNum);
						$(".buy-price-data-sell").val(1.21);
						$(".buy-number-sell").val(dataNum);
						$(".pay-data-sell").html(parseFloat((Number($(".buy-number-sell").val()) * Number($(".buy-price-data-sell").val())).toFixed(2)));
                        //$(".pay-data-sell").html(0);
                        //点击数量+
						$(".add-data").click(function() {
							var num = Number($(".buy-number-sell").val());
							console.log(num);
							if(num >= Number(dataNum)) {
								return;
							}

							num = num + 1;
							$(".buy-number-sell").val(num);
							$(".pay-data-sell").html(parseFloat((Number(num) * Number($(".buy-price-data-sell").val())).toFixed(2)));

						});

						//点击数量-
						$(".reduce-data").click(function() {
							var num = Number($(".buy-number-sell").val());
							if(num <= 0) {
								return;
							}
							num = num - 1;
							$(".buy-number-sell").val(num);
							$(".pay-data-sell").html(parseFloat((Number(num) * Number($(".buy-price-data-sell").val())).toFixed(2)));
						});
						//input框失焦事件
						$(".buy-number-sell").blur(function() {
                            var num = Number($(".buy-number-sell").val());

							    //用户持有数量大于0
                            if(num > Number(dataNum)) {
                                $(".buy-number-sell").val(dataNum);
                                $(".pay-data-sell").html(parseFloat((Number(dataNum) * Number($(".buy-price-data-sell").val())).toFixed(2)));
                                return;
                            }
                            $(".pay-data-sell").html(parseFloat((Number(dataNum) * Number($(".buy-price-data-sell").val())).toFixed(2)));


							//$(".pay-data-sell").html(parseFloat((Number(num) * Number($(".buy-price-data-sell").val())).toFixed(2)));
						});
						//价格失去焦点事件
						$(".buy-price-data-sell").blur(function() {

							price = $(this).val();
							$(".pay-data-sell").html(parseFloat((Number($(".buy-number").val()) * Number(price)).toFixed(2)));
						});
						//卖出确认按钮
						$(".need-buy-sell").click(function() {
						    //点击卖出的时候进行基本判断，如数量或者价格为0的提示

							//点击卖出的时候弹出密码
							price = $(".buy-price-data-sell").val(); //单价
							num = $(".buy-number-sell").val(); //卖出数量
							total_price = $(".pay-data-sell").html(); //总价
                            if(price <= 0){
                                layer.open({
                                    content : "卖出价格不能小于0",
                                    btn : "确定"
                                })
                            }
                            else if(num < 1){
                                layer.open({
                                    content : "卖出数量最少1件",
                                    btn : "确定"
                                })
                            }
                            else{
                                $(".posi-block").css({
                                    display: "block"
                                });
                                $(".input-pass").css({
                                    display: "block"
                                });
                            }


						});
						$(".pay-cancel span").click(function() {
							var payIndex = $(this).index();
							if(payIndex == 0) {
								//确定
								console.log(price, num, total_price, pw);

								$(".posi-block").css({
									"display": "none"
								});
								$(".input-pass").css({
									display: "none"
								});
								$(".input-pass").find("li").find("img").css({
									display: "none"
								});
								$(".input-pass").find("input").val("");
								//拿到需要的数据，发送请求进行处理即可
								$.ajax({
									headers: {
										'accessToken': accessToken,
										contentType: "application/x-www-form-urlencoded"
									},
									type: "post",
									url: "http://www.itoloan.com/api/trade/sellTmc",
									data: {
										price: price,
										num: num,
										total_price: total_price,
										security: pw
									},
									async: true,
									success: function(backState) {
										console.log(backState);

										if(backState.code == 200) {
											console.log("卖出成功");
											//window.location.href = "transaction/" + 0;
                                            sessionStorage.setItem("isIndex","0");
                                            window.location.href = "../transaction/";

										}
										else{
										    layer.open({
                                                content : backState.message,
                                                btn : "确定"
                                            })
                                        }
									},
									dataType: "json"
								})
							} else {
								//取消
								payPass = $(".input-pass input").val();
								$(".posi-block").css({
									"display": "none"
								});
								$(".input-pass").css({
									display: "none"
								});
								$(".input-pass").find("li").find("img").css({
									display: "none"
								});
								$(".input-pass").find("input").val("");
							}
						});
					},
					complete: function(data) {
						console.log(data);
					},
					dataType: "json"
				});

			});

		} else if(loc.indexOf('buy') != -1 && loc.indexOf("buyandsellList") == -1) {
            //买入页面

			$(function() {
				$('.back-button').click(function() {
					history.go(-1);
				});
                var accessToken = sessionStorage.getItem("accessToken");
				var deal_id = Number(sessionStorage.getItem("id"));
				var payStyle = 2; //默认2为余额支付，
				var payPass = ""; //支付密码
				var total_amount; //购买数量
				var total_price; //购买总价
				var pw = '';
				// if(/^[0-9]+$/.test(str)) {
				// 	deal_id = str;
                //
				// } else {
				// 	deal_id = 2
				// }
				//支付方式选择
				$(".pay-style-change").click(function(e) {
                    e.stopPropagation();
					var isNone = $(".posi-block").css("display");

					if(isNone == "none") {
						$(".posi-block").css({
							"display": "block"
						});
						$(".change-pay").css({
							display: "block"
						})
					} else {
						$(".posi-block").css({
							"display": "none"
						});
						$(".change-pay").css({
							display: "none"
						})
					}
				});
				//大的黑盒子点击进行隐藏
				$(".posi-block").click(function(){
                    $(this).css({
                        "display": "none"
                    });
                    $(".change-pay").css({
                        display: "none"
                    })
                });
                $(".change-pay").click(function(e){
                     e.stopPropagation();
                });
				//有蒙版，点击蒙版让选择支付方式隐藏掉，阻止冒泡即可
				// $(".posi-block").click(function () {
				//     $(this).css({display:"none"});
				//     $(".change-pay").css({display:"none"})
				// });
				//选择支付方式，余额或者微信支付
				$(".change-pay li").click(function(e) {
				    e.stopPropagation();
					var liIndex = $(this).index();
					console.log(liIndex);
					if(liIndex == 0) {
						payStyle = 2; //余额支付
						$(".circle1").css({
							backgroundColor: "#427BFF"
						});
						$(".circle2").css({
							backgroundColor: "transparent"
						});
						$(".pay-style").find("span").eq(0).html("余额");
					} else {
						payStyle = 1; //微信支付
						$(".circle2").css({
							backgroundColor: "#427BFF"
						});
						$(".circle1").css({
							backgroundColor: "transparent"
						});
						$(".pay-style").find("span").eq(0).html("微信");
					}
					$(".posi-block").css({
						"display": "none"
					});
					$(".change-pay").css({
						display: "none"
					})
				});
                $(".input-pass").click(function (e) {
                    e.stopPropagation();
                });
				//输入支付密码
				$(".input-pass input").on("input", function(e) {
				    e.stopPropagation();
					var maxLength = 6; //定义最大输入长度

					//每输入一个字符
					var passLen = $(this).val().length;
					if(passLen <= maxLength) {
						$(".input-pass").find("li").each(function() {
							$(this).find("img").css({
								display: "none"
							})
						});
						pw = $(this).val();
						console.log(pw);
						for(var h = 0; h < passLen; h++) {
							$(".input-pass").find("li").eq(h).find("img").css({
								display: "block"
							});

						}
						console.log(passLen)

					} else {
						return;

					}
					// else{
					//     return;
					// }
					payPass = pw;
				});
				//页面打开获取数据
				$.ajax({
					headers: {
                        accessToken: accessToken

					},
					type: "post",
					url: "http://www.itoloan.com/api/trade/buyPage",
					data: {
						"deal_id": deal_id

					},
					async: true,
					success: function(backData) {
						//				console.log(backData.data); //拿到返回数据进行处理
						var data = backData.data;

						$(".user-data-buy").html(data.nickname);
						$(".shengyu-data-buy").html(data.rest_amount);
						$(".buy-price-buy").html(data.price);
						$(".buy-number-buy").html(data.rest_amount);
						//$(".pay-data-buy").html(parseFloat((Number(data.rest_amount) * Number(data.price)).toFixed(2)));
                        $(".pay-data-buy").html(0);

						//--------------------------------
						//点击数量+
						$(".add-data").click(function() {
							var num = Number($(".buy-number-buy").val());
							console.log(num);
							if(num >= Number(data.rest_amount)) {
								return;
							}

							num = num + 1;
							$(".buy-number-buy").val(num);
							$(".pay-data-buy").html(parseFloat((Number(num) * Number(data.price)).toFixed(2)));

						});

						//点击数量-
						$(".reduce-data").click(function() {
							var num = Number($(".buy-number-buy").val());
							if(num <= 0) {
								return;
							}
							num = num - 1;
							$(".buy-number-buy").val(num);
							$(".pay-data-buy").html(parseFloat((Number(num) * Number(data.price)).toFixed(2)));
						});
						//input框失焦事件
						$(".buy-number").blur(function() {
							var num = Number($(".buy-number-buy").val());
							if(num > Number(data.rest_amount)) {
								$(".buy-number-buy").val(data.rest_amount);
								$(".pay-data-buy").html(parseFloat((Number(data.rest_amount) * Number(data.price)).toFixed(2)));
								return;
							}
							$(".pay-data-buy").html(parseFloat((Number(num) * Number(data.price)).toFixed(2)));
						});

						//买入确认
						$(".need-buy-buy").click(function() {
							total_amount = Number($(".buy-number-buy").val()); //购买数量
							total_price = Number($(".pay-data-buy").html()); //购买总价

							//拿到需要的数据，发送请求进行处理即可

							//点击我要买入需要确认是余额还是微信支付方式

							//余额支付

							//输入支付密码后，点击确定或者取消操作
							//点击我要买入之后让input自动聚焦
							//$("#password").focus();
							console.log(payStyle);
							if(payStyle == 2) {
								//余额支付方式
                                if(total_amount == 0){
                                    layer.open({
                                        content : "买入数量不能为0",
                                        btn : "确定"
                                    })
                                }
                                else{
                                    $(".posi-block").css({
                                        display: "block"
                                    });
                                    $(".input-pass").css({
                                        display: "block"
                                    });
                                }


							} else {
							    //买入页面的微信支付方式
								//微信支付方式，当前页面不需要进行输入密码操作，只需要进行请求即可
                                var weixinData = {
                                    "deal_id": deal_id,
                                    "total_amount": total_amount,
                                    "total_price": total_price,
                                    "pay_type": payStyle
                                };
                                var phoneType = sessionStorage.getItem("phoneType");
                                if(phoneType.indexOf("iOS") != -1){
                                    window.webkit.messageHandlers.htmlToIos.postMessage(weixinData);
                                }
                                else{
                                    location.href = "wechatPay="+deal_id+","+total_amount+","+total_price+","+payStyle+"";

                                }



							}

						});
						//输入密码之后进行判断以及请求
						$(".pay-cancel span").click(function(e) {
						    e.stopPropagation();
							var payIndex = $(this).index();

							if(payIndex == 0) {
                                console.log(deal_id);
                                console.log(total_amount);
                                console.log(total_price);
                                console.log(payStyle);
                                console.log(pw);
                                var sendData = {
                                    "deal_id": deal_id,
                                    "total_amount": total_amount,
                                    "total_price": total_price,
                                    "pay_type": payStyle,
                                    "security": pw
                                };
								//确认支付
                                console.log("确认支付")
								console.log(pw);
								console.log(sendData);
								$(".posi-block").css({
									"display": "none"
								});
								$(".input-pass").css({
									display: "none"
								});
								$(".input-pass").find("li").find("img").css({
									display: "none"
								});
								$(".input-pass").find("input").val("");
								console.log(payStyle);
								$.ajax({
									headers: {
                                        accessToken: accessToken

									},
									type: "post",
									url: "http://www.itoloan.com/api/trade/buyTmc",
									// data: {
									// 	"deal_id": deal_id, //记录id
									// 	"total_amount": total_amount, //购买数量
									// 	"total_price": total_price, //购买总价
									// 	"pay_type": payStyle, //支付方式选择
									// 	"security": pw //若是为余额支付则需要支付密码
									// },
                                    data : sendData,
									async: true,
									success: function(backState) {
										console.log(backState);


                                        //window.location.href = "transaction/" + 1;

                                        if(backState.code == 200){
                                            sessionStorage.setItem("isIndex","1");
                                            window.location.href = "../transaction/";
                                        }
                                        else{
                                            layer.open({
                                                content : backState.message,
                                                btn : "确定"
                                            })
                                        }


									},
									dataType: "json"
								})
							} else {
								//取消支付，隐藏即可，什么都不需要做
								console.log("取消支付");
								$(".posi-block").css({
									"display": "none"
								});
								$(".input-pass").css({
									display: "none"
								});
								$(".input-pass").find("li").find("img").css({
									display: "none"
								});
								$(".input-pass").find("input").val("");
								return;
							}
						});

					},
					complete: function(data1) {
						console.log(data1);
					},
					dataType: "json"
				});
				//页面打开调用接口数据，然后对应标签赋值

			});

		} else if(loc.indexOf('transaction') != -1) {

			//transaction.js
			$(function() {
				var accessToken = sessionStorage.getItem("accessToken"); //获取token
				$('.back-button').click(function() {
					history.go(-1);
				});
				console.log(accessToken);
                //我的卖出列表
                function mySellList(){
                    $.ajax({
                        type: "post",
                        headers: {
                            accessToken: accessToken
                        },
                        url: "http://www.itoloan.com/api/trade/mySellList",
                        data: {},
                        async: true,
                        success: function(backData) {
                            console.log(backData.data.sell_lists); //拿到我的卖出列表数据
                            var sellData = backData.data.sell_lists;
                            for(var i = 0; i < sellData.length; i++) {
                                deal_id.push(sellData[i].deal_id);
                                // yearData = sellData[i].created_at.split("  ")[0];
                                // hourData = sellData[i].created_at.split("  ")[1];
                                // allData = yearData + " " + hourData;
                                var str = "<li>\n" +
                                    "                            <div class=\"tran-computed-money\">\n" +
                                    "                                <span>" + sellData[i].total_price + "</span>\n" +
                                    "                            </div>\n" +
                                    "                            <div class=\"tran-unit-price\">\n" +
                                    "                                <span style='margin-left: .08rem;'>￥</span>\n" +
                                    "                                <span>" + sellData[i].unit_price + "</span>\n" +
                                    "                            </div>\n" +
                                    "                            <div class=\"tran-shengYu-all\">\n" +
                                    "                                <span>" + sellData[i].rest_amount + "</span>\n" +
                                    "                                <span>/</span>\n" +
                                    "                                <span>" + sellData[i].total_amount + "</span>\n" +
                                    "                            </div>\n" +
                                    "                            <div class=\"tran-state\">\n" +
                                    "                                <span>" + sellData[i].state + "</span>\n" +
                                    "                                <span>" + sellData[i].create_at + "</span>\n" +
                                    "                            </div>\n" +
                                    "                        </li>";

                                $(".tran-my-sell").append(str);
                                // deal_id.push(sellData[i].deal_id);
                                // console.log(deal_id);
                                if(sellData[i].rest_amount && sellData[i].total_amount) {
                                    if((sellData[i].total_amount - sellData[i].rest_amount) == 0) {
                                        console.log("ok")
                                        //一件都没有卖出去,拿到下标
                                        //checkState.push(i);
                                    }
                                }
                                if(sellData[i].status) {
                                    if(sellData[i].status == 1) {
                                        $(".tran-my-sell").find("li").eq(i).find(".tran-state").find("span").eq(0).html("进行中").css({
                                            color: "#FA5A69"
                                        });
                                        $(".tran-my-sell").find("li").eq(i).find(".tran-shengYu-all").find("span").eq(0).css({
                                            color: "#FA5A69"
                                        });
                                        //$(".tran-my-sell").find("li").eq(i).find(".tran-state").find("span").eq(0).css({color:"#FA5A69"});

                                    } else if(sellData[i].status == 2) {
                                        $(".tran-my-sell").find("li").eq(i).find(".tran-state").find("span").eq(0).html("已取消");
                                    } else {
                                        $(".tran-my-sell").find("li").eq(i).find(".tran-state").find("span").eq(0).html("已完成");
                                    }
                                }

                            }
                            console.log(checkState)

                        },
                        complete: function(data) {
                            console.log(data)
                        },
                        dataType: "json"
                    });
                }
                //我的买入列表
                function myBuyList(){
                    $.ajax({
                        type: "post",
                        headers: {
                            accessToken: accessToken
                        },
                        url: "http://www.itoloan.com/api/trade/myBuyList",
                        data: {},
                        async: true,
                        success: function(backData) {
                            console.log("-------------");
                            console.log(backData);
                            var buyData = backData.data.buy_lists;
                            for(var j = 0; j < buyData.length; j++) {
                                // yearData = buyData[j].created_at.split(" ")[0];
                                // hourData = buyData[j].created_at.split(" ")[1];
                                // allData = yearData + " " + hourData;
                                //console.log(buyData[j].created_at)
                                var str1 = "<li>\n" +
                                    "                            <div class=\"tran-computed-money\">\n" +
                                    "                                <span>"+buyData[j].total_price+"</span>\n" +
                                    "                            </div>\n" +
                                    "                            <div class=\"tran-unit-price\">\n" +
                                    "                                <span>￥</span>\n" +
                                    "                                <span>"+buyData[j].unit_price+"</span>\n" +
                                    "                            </div>\n" +
                                    "                            <div class=\"tran-shengYu-all\">\n" +
                                    "                                <span style='margin-left: .20rem;'>"+buyData[j].total_amount+"</span>\n" +

                                    "                            </div>\n" +
                                    "                            <div class=\"tran-state\">\n" +
                                    "                                <span></span>\n" +
                                    "                                <span>" + buyData[j].create_at + "</span>\n" +
                                    "                            </div>\n" +
                                    "                        </li>";
                                $(".tran-my-pay").append(str1);
                                if(buyData[j].status) {
                                    $(".tran-my-pay").find("li").eq(j).find(".tran-state").find("span").eq(0).html("已完成");
                                }
                            }
                            // $(".tran-my-pay li").click(function () {
                            //     var currentIndex1 = $(this).index();
                            //     if(isIndex==0){
                            //         window.location.href = "sell.html"
                            //     }
                            //
                            // })
                        },
                        dataType: "json"
                    });
                }
                //页面打开之后执行这两个函数
                // mySellList();
                // myBuyList();
				//var isIndex = window.location.href.split("?")[1] ? window.location.href.split("?")[1].split("=")[1] : 0; //用于判断点击下标（我的卖出或我的买入）
				var isIndex = sessionStorage.getItem("isIndex") ? sessionStorage.getItem("isIndex") : 0;
                var isManager = false; //点击管理开关
				var sendCheckedArr = []; //用于存放进行中的卖出任务，存的值为下标
				var checkState = [];
				var checkIndex; //拿到当前选中的下标
				var deal_id = [];
				var send_id = [];
				var yearData, hourData, allData;
				//切换卖出/买入
				function changeSell() {

					$(".tran-my-sell").css({
						display: "block"
					});
					$(".tran-my-pay").css({
						display: "none"
					});
					$(".tran-my-manager").css({
						display: "none"
					});
                    mySellList();
				}

				function changeBuy() {

					$(".tran-my-sell").css({
						display: "none"
					});
					$(".tran-my-pay").css({
						display: "block"
					});
					$(".tran-my-manager").css({
						display: "none"
					});
                    myBuyList();
				}
				//页面打开根据参数判断对应ul进行显示
				(function() {
					$(".tran-sell-buy span").css({
						"font-size": ".13rem",
						fontWeight: "normal"
					});
					$(".tran-sell-buy span").eq(isIndex).css({
						"font-size": ".15rem",
						fontWeight: "bold"
					});
					if(isIndex == 0) {
                        $(".tran-my-sell").find("li").remove();
                        $(".tran-sell-buy-title").find("span").eq(2).html("剩余数量/总数量")
						changeSell();
					} else {
                        $(".tran-my-pay").find("li").remove();
                        $(".tran-sell-buy-title").find("span").eq(2).html("数量")
						changeBuy()
					}
				})();
                //点击进行切换，调用方法
				$(".tran-sell-buy span").click(function() {
				    //点击的时候改变isIndex的值来进行切换
					isIndex = $(this).index();
					console.log(isIndex);
					$(".tran-sell-buy span").css({
						"font-size": ".13rem",
						fontWeight: "normal"
					});
					$(this).css({
						"font-size": ".15rem",
						fontWeight: "bold"
					});
					// $("tran-sell-buy-con").find("ul").css({display:"none"});
					// $("tran-sell-buy-con").find("ul").eq(isIndex).css({display:"block"});
					if(isIndex === 0) {
						// $(".tran-my-sell").css({
						// 	display: "block"
						// });
						// $(".tran-my-pay").css({
						// 	display: "none"
						// });
						// $(".tran-my-manager").css({
						// 	display: "none"
						// });
                        $(".tran-my-sell").find("li").remove();
						$(".tran-sell-buy-title").find("span").eq(2).html("剩余数量/总数量");
                        changeSell();
					} else {
                        $(".tran-my-pay").find("li").remove();
					    if(isManager == true){
                            $(".tran-dan-checked").css({
                                display: "none",
                                margin: " 0"
                            });
                            $(".footer-isDelete").css({
                                display: "none"
                            });
                            isManager = false;
                        }
						// $(".tran-my-sell").css({
						// 	display: "none"
						// });
						// $(".tran-my-pay").css({
						// 	display: "block"
						// });
						// $(".tran-my-manager").css({
						// 	display: "none"
						// });
                        $(".tran-sell-buy-title").find("span").eq(2).html("数量");
					    changeBuy();
					}
				});



				//点击管理按钮

				/**
				 * 点击管理
				 * 1：我的卖出进行订单删除
				 * 2：让其与ul隐藏掉即可
				 * 3：判断条件为一件都没有卖出去
				 */
				$(".transaction-record span").click(function() {
					if(isManager == false && isIndex == 0) {
						checkState = [];
						console.log(checkState);
						isManager = true;
						$.ajax({
							type: "post",
							headers: {
                                accessToken: accessToken
							},
							url: "http://www.itoloan.com/api/trade/delTradePage",
							data: {},
							async: true,
							success: function(backData) {
								$(".tran-sell-buy-con ul").css({
									display: "none"
								});
								console.log(backData.data); //拿到我的卖出列表数据
								var managerData = backData.data;
								//-----------------------------
								for(var k = 0; k < managerData.length; k++) {
									var str = "<li>\n" +
										"                            <div class=\"tran-dan-checked\">\n" +
										"                                <input type=\"checkbox\" class=\"check\">\n" +
										"                                <!--<div class=\"tran-check-bg\"></div>-->\n" +
										"                            </div>\n" +
										"                            <div class=\"tran-computed-con\">\n" +
										"                                <div class=\"tran-computed-money\">\n" +
										"                                    <span>" + managerData[k].total_price + "</span>\n" +
										"                                </div>\n" +
										"                                <div class=\"tran-unit-price\">\n" +
										"                                    <span>￥</span>\n" +
										"                                    <span>" + managerData[k].unit_price + "</span>\n" +
										"                                </div>\n" +
										"                                <div class=\"tran-shengYu-all\">\n" +
										"                                    <span>" + managerData[k].rest_amount + "</span>\n" +
										"                                    <span>/</span>\n" +
										"                                    <span>" + managerData[k].total_amount + "</span>\n" +
										"                                </div>\n" +
										"                                <div class=\"tran-state\">\n" +
										"                                    <span>进行中</span>\n" +
										"                                    <span>" + managerData[k].create_at + "</span>\n" +
										"                                </div>\n" +
										"                            </div>\n" +
										"\n" +
										"                        </li>";
									$(".tran-my-manager").append(str);
									if(managerData[k].status) {
										if(managerData[k].status == 1) {
											$(".tran-my-sell").find("li").eq(k).find(".tran-state").find("span").eq(0).html("进行中");
											//.css({color:"#FA5A69"});
											//$(".tran-my-sell").find("li").eq(i).find(".tran-shengYu-all").find("span").eq(0).css({color:"#FA5A69"});
											//$(".tran-my-sell").find("li").eq(i).find(".tran-state").find("span").eq(0).css({color:"#FA5A69"});
											//checkState.push(i);

										}
										// else if(managerData[k].status == 2){
										//     $(".tran-my-sell").find("li").eq(i).find(".tran-state").find("span").eq(0).html("已取消");
										// }
										// else{
										//     $(".tran-my-sell").find("li").eq(i).find(".tran-state").find("span").eq(0).html("已完成");
										// }
									}
								}

								//-----------------------------
								//待标签for循环创建完毕之后再进行一系列操作
								$(".tran-sell-buy-title").css({
									marginLeft: "10%"
								});

								$(".tran-sell-buy-con").find(".tran-my-manager").css({
									display: "block"
								});

								//$(".tran-computed-con").css({width:"90%"});
								$(".tran-dan-checked").css({
									display: "block",
									margin: "-.40rem 0"
								});
								$(".footer-isDelete").css({
									display: "block"
								});
								//-----------------------------
								console.log(sendCheckedArr);
								//监听input框选中状态
								$(".check").on("ifChecked", function(event) {

									//拿到当前选中的行下标
									checkIndex = $(this).parent().parent().parent().index();

									if(checkState.indexOf(checkIndex) == -1) {
										checkState.push(checkIndex);
									}
									console.log(checkState);
									console.log(checkIndex);
									//进行状态判断，拿到进行中的订单
									// sendCheckedArr.push(checkState[checkIndex]);
									// console.log(sendCheckedArr);
									//此处进行删除操作以后，我的卖出页面ul需重新创建渲染，因为数据库数据已改变

								});
								//监听input框取消选中状态
								$(".check").on("ifUnchecked", function() {

									//拿到先进行选中然后又取消选中的行下标
									//并且需要把sendCheckedArr里面的对应值删掉
									checkIndex = $(this).parent().parent().parent().index();

									//进行状态判断，拿到进行中的订单
									//删除值需要值对应，不能用下标删除
									if(checkState.indexOf(checkIndex) > -1) {
										var testIndex = checkState.indexOf(checkIndex);
										checkState.splice(testIndex, 1);
									}
									console.log(checkState);
									console.log(checkIndex);
									// if(sendCheckedArr.indexOf(checkState[checkIndex]) > -1){
									//     var testIndex = sendCheckedArr.indexOf(checkState[checkIndex]);
									//     sendCheckedArr.splice(testIndex,1);
									// }
									//
									// console.log(sendCheckedArr);
								});
								//初始化复选框
								$(".check").iCheck({
									checkboxClass: 'icheckbox_square-blue',
									radioClass: 'iradio_square-blue',
									increaseArea: '20%' // optional

								});

								//取消按钮操作
								$(".cancel-delete").click(function() {
									//移除所有的多选选中
									$(".check").each(function() {
										$(this).iCheck("uncheck");
									})
									checkState = [];
								});
								//确认按钮操作
								$(".ok-delete").click(function() {
									send_id = [];
									console.log(checkState);
									for(var k = 0; k < checkState.length; k++) {
										if(send_id.indexOf(managerData[checkState[k]].deal_id) == -1) {
											send_id.push(managerData[checkState[k]].deal_id)
										}

									}
									console.log(send_id); //拿到要传的下标
									$.ajax({
										type: "post",
										headers: {
                                            accessToken: accessToken
										},
										url: "http://www.itoloan.com/api/trade/delTrade",
										data: {
											"deal_id": send_id
										},
										async: true,
										success: function(backData) {
											console.log(backData);
											//完成之后重新渲染我的卖出页面

											//我的卖出列表
											window.location.reload(true);
										}
									})
								});
							},
							complete: function(data) {
								console.log(data)
							},
							dataType: "json"
						});
					} else if(isManager == true && isIndex == 0) {
						$(".tran-sell-buy-con ul").css({
							display: "none"
						});
						$(".tran-sell-buy-con").find("ul").eq(isIndex).css({
							display: "block"
						});
						$(".tran-sell-buy-title").css({
							marginLeft: "0"
						});
						//$(".tran-computed-con").css({width:"100%"});
						$(".tran-dan-checked").css({
							display: "none",
							margin: " 0"
						});
						$(".footer-isDelete").css({
							display: "none"
						});
						$(".tran-my-manager").find("li").remove();
						isManager = false;
					} else {
						return;
					}
				});
			});

		}

	} else {
		alert('请先登录')
	}

}

//==============
